package org.opensuse.bs.ui;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE.SharedImages;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * The activator class controls the plug-in life cycle
 */
public class BSUIPlugin extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "org.opensuse.bs.ui";

	// The shared instance
	private static BSUIPlugin plugin;
	
	//.oscrc file
	private File oscrc;
	private String home = System.getProperty("user.home");	
	private HashMap<String, HashMap<String, String>> sections;
	
	private Vector<String> aimedPrjs;
	private Map<String, String> distros;
	private String apiurl;
	private String user;
		
	private ImageRegistry imageDescriptors = new ImageRegistry();
	
	private void createImageDescriptor(String id, boolean locale) {
		ImageDescriptor desc;
		if(locale) {
			URL url = FileLocator.find(BSUIPlugin.getDefault().getBundle(), new Path(IBSUIConstants.ICON_PATH + id), null);
			desc = ImageDescriptor.createFromURL(url);
		}
		else {
			Image img = PlatformUI.getWorkbench().getSharedImages().getImage(id);
			desc = ImageDescriptor.createFromImage(img);
		}
		
		imageDescriptors.put(id, desc);
	}
	
	private void initializeImages() {
		createImageDescriptor(IBSUIConstants.IMG_REFRESH, true);
		createImageDescriptor(IBSUIConstants.IMG_REFRESH_ENABLED, true);
		createImageDescriptor(IBSUIConstants.IMG_REFRESH_DISABLED, true);
		createImageDescriptor(IBSUIConstants.IMG_COLLAPSE_ALL, true);
		createImageDescriptor(IBSUIConstants.IMG_COLLAPSE_ALL_ENABLED, true);
		createImageDescriptor(IBSUIConstants.IMG_REMOTE_ENTRY, true);
		createImageDescriptor(IBSUIConstants.IMG_LOCALE_ENTRY, true);
		createImageDescriptor(IBSUIConstants.IMG_SPEC_FILE, true);
		createImageDescriptor(IBSUIConstants.IMG_PACKAGE_FILE, true);
		createImageDescriptor(IBSUIConstants.IMG_JAR_FILE, true);
		createImageDescriptor(IBSUIConstants.IMG_LIST_ALL, true);
		createImageDescriptor(IBSUIConstants.IMG_LIST_WATCHlIST, true);
		createImageDescriptor(IBSUIConstants.IMG_UPLOAD, true);
		createImageDescriptor(ISharedImages.IMG_OBJ_FILE, false);
		createImageDescriptor(SharedImages.IMG_OBJ_PROJECT, false);
		createImageDescriptor(ISharedImages.IMG_OBJ_FOLDER, false);
	}
	
	/* hard code the whole distros.  
	 * (key, value) maps to 
	 * (repos name="key", repo project="value/standard")
	 */ 
	private void initDistros() {
		distros = new HashMap<String, String>();
		distros.put("openSUSE_11.0", "openSUSE:11.0");
		distros.put("openSUSE_10.3", "openSUSE:10.3");
		distros.put("openSUSE_10.2", "openSUSE:10.2");
		distros.put("openSUSE_Factory", "openSUSE:Factory");
		distros.put("SLE_10", "SUSE:SLE-10:SDK");
		distros.put("SLES_9", "SUSE:SLES-9");
		distros.put("Debian_Etch", "Debian:Etch");
		distros.put("xUbuntu_8.04", "Ubuntu:8.04");
		distros.put("xUbuntu_7.10", "Ubuntu:7.10");
		distros.put("xUbuntu_7.04", "Ubuntu:7.04");
		distros.put("xUbuntu_6.06", "Ubuntu:6.06");
		distros.put("Fedora_9", "Fedora:9");
		distros.put("Fedora_8", "Fedora:8");
		distros.put("RHEL_5", "RedHat:RHEL-5");
		distros.put("CentOS_5", "CentOS:CentOS-5");
		distros.put("Mandriva_2008", "Mandriva:2008");
		distros.put("Mandriva_2007", "Mandriva:2007");
	}
	
	/**
	 * The constructor
	 */
	public BSUIPlugin() {
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
		
		//debug
		//IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		//System.out.println(root.getProjects().length);
		
		oscrc = new File(home+"/.oscrc");
		if(!oscrc.exists()) {
			MessageDialog.openWarning(null, "Build Servie Plugin", 
					"Build Servie Plugin cannot work properly without .oscrc. Please create " +
					".oscrc in your home directory, either running \"osc\" in a terminal or" +
					" creating manually.");
			return;
		}
		Parser parser = new Parser(oscrc);
		sections = parser.parse();
		HashMap<String, String> general = sections.get("general");
		if(general == null)
			apiurl = "api.opensuse.org";
		else {
			String apisrv = general.get("apisrv");
			if(apisrv == null)
				apiurl = "api.opensuse.org";
			else
				apiurl = apisrv;
		}
		Set<String> keys = sections.keySet();
		for(String key : keys) {
			if(key.indexOf(apiurl) != -1 || apiurl.indexOf(key) != -1) {
				user = sections.get(key).get("user");
				break;
			}
		}
		
		aimedPrjs = new Vector<String>();
		initializeImages();
		initDistros();
		//read checked projects from saved status file
		/*ISaveParticipant saveParticipant = new BSWorkspaceSaveParticipant();
       ISavedState lastState = 
    	   ResourcesPlugin.getWorkspace().addSaveParticipant(this, saveParticipant);
       if (lastState == null)
    	   return;
       IPath location = lastState.lookup(new Path("save"));
       if (location == null)
    	   return;
       File f = getStateLocation().append(location).toFile();
       FileReader in = new FileReader(f);
       BufferedReader input = new BufferedReader(in);
       String line;
       while((line = input.readLine()) != null) {
    	   if(! line.trim().isEmpty())
    	   involved.add(line.trim());
       }
       input.close();*/
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
		sections.clear();
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static BSUIPlugin getDefault() {
		return plugin;
	}
	
	public HashMap<String, HashMap<String, String>> getSections() {
		return sections;
	}
	
	public void setUser(String user) {
		this.user = user;
	}
	
	public String getUser() {
		return user;
	}
	
	public void setApiurl(String url) {
		this.apiurl = url;
	}
	
	public String getApiurl() {
		return apiurl;
	}
	
	public File getOscrc() {
		return oscrc;
	}
	
	public Vector<String> getAimed() {
		return aimedPrjs;
	}
	
	public Map<String, String> getDistros() {
		return distros;
	}
	
	public String[] getInvolvedProject() {
		try {
			Document doc = OSC.toXML("req /search/project?match=%5Bperson%2F%40userid%3D%27"+user+"%27%5D");
			if(doc == null) {
				return new String[0];
			}
			NodeList list = doc.getElementsByTagName("project");
			int size = list.getLength();
			if(size != 0) {
				String[] prjs = new String[size];
				for(int i=0;i<size;i++) {
					Element prj = (Element) list.item(i);
					prjs[i] = prj.getAttribute("name");
				}
				return prjs;
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return new String[0];
	}
	
	public ImageDescriptor getImageDescriptor(String id) {
		return imageDescriptors.getDescriptor(id);
	}
}
